<template>
  <div class="edmit-address common-page">
    <van-form>
      <div class="info-box">
        <van-field
          v-model="addressInfo.name"
          placeholder="请输入收货人姓名"
          label="收货人"
          :rules="[{ required: true, message: '请输入收货人姓名' }]"
        />
        <van-field
          v-model="addressInfo.tel"
          placeholder="请输入收货人手机号"
          label="手机号"
          :rules="[{ required: true, message: '请输入合法手机号' }]"
          maxlength="11"
        />
        <van-field
          v-model="provinceCtiy"
          readonly
          placeholder="请选择省市区"
          label="所在地区"
          is-link
          @click="showArea"
          :rules="[{ required: true, message: '请选择省市区' }]"
        />
        <van-field
          v-model="addressInfo.address"
          rows="2"
          autosize
          label="详细地址"
          type="textarea"
          placeholder="如道路、门牌号、小区、楼栋号、单元等"
          :rules="[{ required: true, message: '请输入详细地址' }]"
        />
      </div>
      <van-cell
        center
        title="设为默认"
        class="set-default"
      >
        <van-switch
          v-model="checked"
          slot="right-icon"
          size="24"
        />
      </van-cell>
      <div class="remark-box">
        <span>重要：</span>
        <span class="remark">若您所获得的商品并非您所需要产品，可联系客服QQ:{{contentInfo.qq}},或微信：{{contentInfo.wechat}}，兑换为不低于10元且不超过该商品实际价值的80%蔚来校园现金券。</span>
        <span>部分等额商品可替换，当抽中“a商品或b商品”产品时，可任选其一，可在详细地址中备注选择的a或b商品，若不备注即视为随机发货</span>
        <span class="remark">若您抽到的商品为虚拟商品（如会员等），请在详细地址中填写您对应平台账号。腾讯视频用户QQ登录的直接填写QQ号；微信登录的填写绑定腾讯视频的手机号，该手机号务必先在腾讯视频上面绑定微信。</span>
        <span class="remark">其他平台会员账号可直接填写手机号充值</span>
      </div>
      <div :class="!showDelete?'button-box':'button-box save-delete-box'">
        <van-button
          v-if="showDelete"
          type="default"
          round
          @click="onDelete"
        >删除</van-button>
        <van-button
          type="primary"
          round
          native-type="submit"
          @click="onSave"
        >保存</van-button>
      </div>
    </van-form>
    <area-popup-cascader
      ref="areaPopup"
      title="请选择所在地区"
      @setSelectArea="setSelectArea"
      :provinceCode="addressInfo.provinceCode"
      :cityCode="addressInfo.cityCode"
      :districtCode="addressInfo.districtCode"
    ></area-popup-cascader>
    <dialog-custom
      ref="dialog"
      title="确定删除吗？"
      confirmButtonText="删除"
      :showCancelButton="true"
      cancelButtonText="取消"
      confirmButtonColor="#DF5438"
      @confirm="deleteAddress"
    ></dialog-custom>
  </div>
</template>

<script>
import DialogCustom from "@/components/DialogCustom";
import AreaPopupCascader from "@/components/AreaPopupCascader";
import {
  Form,
  Button,
  AddressEdit,
  Field,
  Area,
  Cell,
  Switch,
  Picker,
} from "vant";
import store from "@/store";
import { mapGetters } from "vuex";
import apiAddress from "@/common/api/apiAddress";
import apBox from "@/common/api/apBox";
import utilTool from "@/common/utils/utils";
import Share from "./mixin/share";
export default {
  name: "EdmitAddress",
  components: {
    [DialogCustom.name]: DialogCustom,
    [AreaPopupCascader.name]: AreaPopupCascader,
    [DialogCustom.name]: DialogCustom,
    [Form.name]: Form,
    [Button.name]: Button,
    [Field.name]: Field,
    [Cell.name]: Cell,
    [Switch.name]: Switch,
    [Area.name]: Area,
    [Picker.name]: Picker,
  },
  mixins: [Share],
  data() {
    return {
      searchResult: [],
      addressInfo: {
        userId: "",
        name: "",
        tel: "",
        provinceCode: "",
        cityCode: "",
        districtCode: "",
        address: "",
        default: false,
        districtCN: "",
      },
      checked: false,
      showDelete: false,
      value: "",
      provinceCtiy: "",
      contentInfo: {},
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  watch: {
    checked: function (val) {
      if (val) {
        this.addressInfo.default = 1;
      }
      if (!val) {
        this.addressInfo.default = 0;
      }
    },
  },
  created() {
    this.addressInfo.userId = this.userInfo.userId;
    if (this.$route.query.addressInfo) {
      let addressInfo = JSON.parse(this.$route.query.addressInfo);
      if (addressInfo && addressInfo.id) {
        this.addressInfo = utilTool.deepClone(addressInfo);
        this.$set(this.addressInfo, "id", addressInfo.id);
        this.$set(this.addressInfo, "userId", this.userInfo.userId);
        this.checked = addressInfo.default ? true : false;
      }
      if (this.addressInfo.id) {
        this.showDelete = true;
      }
    }
    this.getContent();
    this.setShare();
  },
  mounted() {},
  methods: {
    //  展示区域选择弹框
    showArea() {
      this.$refs.areaPopup.showArea();
    },
    // 设置提交数据
    setSelectArea(info) {
      this.provinceCtiy = info.fieldValue;
      this.addressInfo.provinceCode = info.selectedOptions[0].areaCode;
      this.addressInfo.cityCode = info.selectedOptions[1].areaCode;
      this.addressInfo.districtCode = info.selectedOptions[2].areaCode;
      this.addressInfo.districtCN = info.districtCN;
    },
    //  保存
    onSave(values) {
      if (
        !this.addressInfo.name ||
        !this.addressInfo.tel ||
        !this.addressInfo.provinceCode ||
        !this.addressInfo.cityCode ||
        !this.addressInfo.districtCode ||
        !this.addressInfo.address ||
        !this.addressInfo.districtCN
      ) {
        return;
      }
      if (this.addressInfo.tel.length !== 11) {
        return this.$toast.err("请输入正确的手机号");
      }
      if (this.addressInfo.id) {
        let addressInfo = utilTool.deepClone(this.addressInfo);
        addressInfo.default = this.checked ? 1 : 0;
        this.edmitAddress(addressInfo);
      }
      if (!this.addressInfo.id) {
        let addressInfo = utilTool.deepClone(this.addressInfo);
        addressInfo.default = this.addressInfo.default ? 1 : 0;
        this.addNewAddress(addressInfo);
      }
    },
    //  新增地址
    addNewAddress(addressInfo) {
      this.$toast.loading();
      apiAddress.addOredmitAddress(JSON.stringify(addressInfo)).then((data) => {
        this.$toast.clear();
        this.saveSuccess();
      });
    },
    //  保存成功
    saveSuccess() {
      this.$toast.success("添加成功");
      this.getAddressList();
    },
    // 编辑地址
    edmitAddress(addressInfo) {
      this.$toast.loading();
      apiAddress.addOredmitAddress(JSON.stringify(addressInfo)).then((data) => {
        this.$toast.clear();
        this.edmitSuccess();
      });
    },
    //  保存成功
    edmitSuccess() {
      this.$toast.success("修改成功");
      this.getAddressList();
      this.getDefaultAddress();
    },
    // 点击删除按钮
    onDelete(content) {
      this.$refs.dialog.showDialog();
    },
    // 删除地址
    deleteAddress() {
      this.$toast.loading();
      apiAddress.deleteAddress({ id: this.addressInfo.id }).then((data) => {
        this.$toast.clear();
        this.deleteAddressSuccess();
      });
    },
    //  删除成功
    deleteAddressSuccess() {
      this.$toast.success("删除成功");
      this.getAddressList();
      this.getDefaultAddress();
    },
    //  获取地址列表
    getAddressList() {
      this.$toast.loading();
      apiAddress
        .getAddressList({
          userId: this.userInfo.userId,
        })
        .then((data) => {
          this.$toast.clear();
          this.getAddressListSuccess(data.data);
        });
    },
    //  获取列表地址成功
    getAddressListSuccess(list) {
      store.dispatch("address/setAddressListIUnfo", list);
      let tempArr = list.filter((item) => {
        return item.default;
      });
      if (tempArr.length) {
        store.dispatch("address/setDefaultAddressInfo", tempArr[0]);
      }
      this.$router.back();
    },
    //  获取默认地址
    getDefaultAddress() {
      this.$toast.loading();
      apiAddress
        .getDefaultAddress({
          userId: this.userInfo.userId,
        })
        .then((data) => {
          this.$toast.clear();
          if (data.data) {
            store.dispatch("address/setDefaultAddressInfo", data.data);
            return;
          }
          store.dispatch("address/setDefaultAddressInfo", {});
        });
    },
    // 获取联系信息
    getContent() {
      this.$toast.loading();
      apBox.getBoxRuleContact().then((data) => {
        this.$toast.clear();
        let content = {};
        if (data.data.content) {
          content = JSON.parse(data.data.content);
        }
        this.contentInfo = content;
      });
    },
  },
};
</script>

<style lang="less" scoped>
@import "../common/css/common.less";
.edmit-address {
  padding-bottom: 114px;
  box-sizing: border-box;
}
.van-address-edit {
  padding: 0;
}

.info-box {
  width: 100%;
  height: auto;
  background: #ffffff;
  border-radius: 12px;
  overflow: hidden;
}

.set-default {
  background: #ffffff;
  border-radius: 12px;
  margin-top: 20px;
}
.button-box.save-delete-box {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  .van-button--default {
    background: #ffffff;
    border: 2px solid #df5438;
    color: #df5438;
    margin-right: 20px;
  }
}
.remark-box {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  width: 100%;
  height: auto;
  padding: 24px;
  box-sizing: border-box;
  span {
    display: inline-block;
    margin-top: 24px;
    box-sizing: border-box;
    font-size: 26px;
    color: red;
    line-height: 40px;
  }
}
</style>
